// src/apis/auth.js
import axiosInstance from '@/apis/axiosInstance';

/**
 * 登录并获取用户信息
 * @param {string} account - 用户账号
 * @param {string} password - 用户密码
 * @returns {Promise} 返回用户信息的Promise
 */
export const login = async (account, password) => {
    console.log('发送登录请求:', { account, password });
    try {
        const formData = new URLSearchParams();
        formData.append('account', account);
        formData.append('password', password);
        
        const response = await axiosInstance.post('/auth/login', formData, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        });
        console.log('登录响应:', response.data);
        return response.data;
    } catch (error) {
        console.error('登录失败:', error.response ? error.response.data : error.message);
        throw error;
    }
};

/**
 * 注册新用户
 * @param {Object} userData - 用户注册数据
 * @param {string} userData.account - 用户账号
 * @param {string} userData.password - 用户密码
 * @param {string} userData.username - 用户名
 * @returns {Promise} 返回注册结果的Promise
 */
export const register = async (userData) => {
    console.log('发送注册请求:', userData);
    try {
        const response = await axiosInstance.post('/auth/register', userData, {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        console.log('注册响应:', response.data);
        return response.data;
    } catch (error) {
        console.error('注册失败:', error.response ? error.response.data : error.message);
        throw error;
    }
};

/**
 * 检查账号是否存在
 * @param {string} account - 要检查的账号
 * @returns {Promise<boolean>} 返回账号是否存在的Promise
 */
export const checkAccountExists = async (account) => {
    try {
        const response = await axiosInstance.get(`/auth/check-account?account=${account}`);
        return response.data.data;
    } catch (error) {
        console.error('检查账号失败:', error.response ? error.response.data : error.message);
        throw error;
    }
};

/**
 * 检查用户名是否存在
 * @param {string} username - 要检查的用户名
 * @returns {Promise<boolean>} 返回用户名是否存在的Promise
 */
export const checkUsernameExists = async (username) => {
    try {
        const response = await axiosInstance.get(`/auth/check-username?username=${username}`);
        return response.data.data;
    } catch (error) {
        console.error('检查用户名失败:', error.response ? error.response.data : error.message);
        throw error;
    }
};